#include <QPixmap>
#include <QPushButton>

#include "centerkeydialog.h"
#include "ui_centerkeydialog.h"

CEnterKeyDialog::CEnterKeyDialog(CDatabase &db, QWidget *parent) :
    QDialog(parent), m_ui(new Ui::CEnterKeyDialog),
    m_db(db), m_isNew(false)
{
    m_ui->setupUi(this);

    connect(m_ui->keyEdit, SIGNAL(textChanged(QString)), this, SLOT(checkKey(QString)));

    m_isNew = !m_db.isOpen();

    if(m_isNew)
        m_ui->iconLbl->setPixmap(QPixmap(":/icons/accept"));
    else
        m_key = m_db.getKeyMd5();

    m_ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(m_isNew);

    m_ui->md5Lbl->setText(QString(32, '0'));
}

CEnterKeyDialog::~CEnterKeyDialog()
{
    delete m_ui;
}

void CEnterKeyDialog::changeEvent(QEvent *e)
{
    QDialog::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        m_ui->retranslateUi(this);
        break;
    default:
        break;
    }
}

void CEnterKeyDialog::checkKey(const QString &key)
{
    QString key_md5 = CDatabase::genMd5(key);
    m_ui->md5Lbl->setText(key_md5);

    if(m_isNew)
        return;

    bool ok = (m_key == key_md5);
    m_ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(ok);
    if(ok)
        m_ui->iconLbl->setPixmap(QPixmap(":/icons/accept"));
    else
        m_ui->iconLbl->setPixmap(QPixmap(":/icons/reject"));
}

QString CEnterKeyDialog::key()
{
    return m_ui->keyEdit->text();
}
